package com.ruoyi.common.utils;

import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.opencv.global.opencv_imgproc;
import org.bytedeco.opencv.opencv_core.Rect;
import org.bytedeco.opencv.opencv_core.Scalar;
import org.bytedeco.opencv.opencv_core.Size;

import static org.bytedeco.opencv.global.opencv_imgproc.*;

public class VideoZoomOut {
    public static void main(String[] args) throws Exception {
        // 1. 输入/输出文件路径
        String inputFile = "D:\\BaiduNetdiskDownload\\宠物异常行为\\狗采集1327-0623\\6.24+1327\\狗\\生成\\宠物喝水\\B01166.mp4";
        String outputFile = "C:\\Users\\lenovo\\Desktop\\far\\B01166.mp4";

        // 2. 初始化抓取器（读取视频）
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
        grabber.start();

        // 3. 获取视频信息
        int width = grabber.getImageWidth();
        int height = grabber.getImageHeight();
        int framesPerSecond = (int) grabber.getFrameRate();
        int totalFrames = grabber.getLengthInFrames();

        // 4. 初始化录制器（写入处理后的视频）
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
                outputFile, width, height
        );
        recorder.setFrameRate(framesPerSecond);
        recorder.setVideoCodec(grabber.getVideoCodec());
        recorder.start();

        // 5. 缩放比例（0.8表示缩小到80%）
        double zoomFactor = 0.8;

        // 6. 逐帧处理
        Frame frame;
        while ((frame = grabber.grabFrame()) != null) {
            if (frame.image != null) {
                // 转换为OpenCV Mat
                Mat mat = Java2DFrameUtils.toMat(frame);

                // 计算缩放后的尺寸
                int newWidth = (int) (width * zoomFactor);
                int newHeight = (int) (height * zoomFactor);

                // 缩放图像
                Mat resized = new Mat();
                resize(mat, resized, new Size(newWidth, newHeight));

                // 创建黑色背景画布
                Mat canvas = new Mat(height, width, mat.type(), new Scalar(0, 0, 0, 0));

                // 将缩放后的图像居中绘制到画布
                int x = (width - newWidth) / 2;
                int y = (height - newHeight) / 2;
                Mat roi = canvas.apply(new Rect(x, y, newWidth, newHeight));
                resized.copyTo(roi);

                // 转换回Frame并写入输出
                Frame processedFrame = Java2DFrameUtils.toFrame(canvas);
                recorder.record(processedFrame);
            }
        }

        // 7. 释放资源
        recorder.stop();
        recorder.release();
        grabber.stop();
        grabber.release();
    }
}
